<?php
add_filter('wpjam_pages', 'wpjam_devices_admin_pages');
add_filter('wpjam_network_pages', 'wpjam_devices_admin_pages');
function wpjam_devices_admin_pages($wpjam_pages){
	$capability	= (is_multisite())?'manage_site':'manage_options';

	$wpjam_pages['wpjam-devices']	= array(
		'menu_title'	=> '移动设备',
		'capability'	=> $capability,
		'icon'			=> 'dashicons-smartphone',
		'position'		=> '25.2'
	);

	return $wpjam_pages;
}

function wpjam_devices_page_load(){
	global $wpjam_list_table;

	$columns		= array(
		'cb'		=> 'checkbox',
		'device'	=> '型号',
		'name'		=> '名称',
		'brand'		=> '品牌',
		'size'		=> '尺寸'
	);

	$wpjam_list_table = wpjam_list_table( array(
		'plural'			=> 'wpjam-devices',
		'singular' 			=> 'wpjam-device',
		'item_callback'		=> 'wpjam_device_item',
		'columns'			=> $columns,
		'sortable_columns'	=> array('size'=>'size'),
		'actions_column'	=> 'device',
		'bulk_actions'		=> array('delete' => '删除')
	) );
}

function wpjam_devices_page(){
	$action = isset($_GET['action'])?$_GET['action']:'';

	if($action == 'edit' || $action == 'add' ){
		wpjam_device_edit_page();
	}else{
		wpjam_device_list_page();
	}
}

function wpjam_device_list_page(){
	global $wpdb, $wpjam_list_table, $current_admin_url;

	$action = $wpjam_list_table->current_action();

	if($action == 'delete'){
		if( !current_user_can( 'manage_options' )){
	    	ob_clean();
	        wp_die('无权限');
	    }
	    if(!empty($_GET['id'])){
			check_admin_referer('delete-'.$wpjam_list_table->get_singular().'-'.$_GET['id']);

			if($wpdb->delete($wpdb->devices, array('id' => $_GET['id']))){
				wpjam_delete_remote_device($_GET['id']);
				wpjam_admin_add_error('删除成功');
			}else{
				wpjam_admin_add_error('删除失败：'.$wpdb->last_error,'error');
			}
		}elseif (!empty($_GET['ids'])) {
			check_admin_referer('bulk-'.$wpjam_list_table->get_plural());

			$error = false;
			foreach ($_GET['ids'] as $id) {
				if(!$wpdb->delete($wpdb->devices, array('id' => $id))){
					wpjam_delete_remote_device($id);
					$error = true;
					wpjam_admin_add_error($id.'删除失败：'.$wpdb->last_error,'error');
				}
			}
			if($error == false){
				wpjam_admin_add_error('删除成功');
			}
		}
	}

	?>
	<h2>移动设备<a title="新增手机设备" class="thickbox add-new-h2" href="<?php echo $current_admin_url.'&action=add'.'&TB_iframe=true&width=780&height=360'; ?>">新增</a></h2>

	<?php

	$type			= isset($_GET['type']) ? $_GET['type'] : '';
	$search_term	= isset($_GET['s']) ? $_GET['s'] : '';

	$where			= "1=1";

	if($search_term){
		$where		.= " AND ( name like '%{$search_term}%' OR device like '%{$search_term}%' OR brand like '%{$search_term}%' )";
	}

	$orderby		= isset($_GET['orderby'])?$_GET['orderby']:'';
	$order 			= isset($_GET['order'])?$_GET['order']:'desc';

	$sql_orderby	= ' id DESC';
	if($orderby){
		$sql_orderby	= "{$orderby} {$order}";
	}

	$limit		= $wpjam_list_table->get_limit();
	$devices	= $wpdb->get_results("SELECT SQL_CALC_FOUND_ROWS * FROM {$wpdb->devices} WHERE {$where} ORDER BY {$sql_orderby} LIMIT {$limit};", ARRAY_A);
	$total		= $wpdb->get_var("SELECT FOUND_ROWS();");

	$wpjam_list_table->prepare_items($devices, $total);
	$wpjam_list_table->display();	
}

function wpjam_device_item($item){
	global $wpjam_list_table, $current_admin_url;

	$item['row_actions'] = array(
		'edit'		=> '<a href="'.$current_admin_url.'&action=edit&id='.$item['id'].'&TB_iframe=true&width=780&height=360'.'" title="编辑手机设备" class="thickbox" >编辑</a>',
		'duplicate'	=> '<a href="'.$current_admin_url.'&action=add&duplicate_id='.$item['id'].'&TB_iframe=true&width=780&height=360'.'" title="复制手机设备" class="thickbox" >复制</a>',
		'delete'	=> '<a href="'.esc_url(wp_nonce_url($current_admin_url.'&action=delete&id='.$item['id'].'&TB_iframe=true&width=780&height=380', 'delete-'.$wpjam_list_table->get_singular().'-'.$item['id'])).'">删除</a>'
	);

	return $item;	
}

function wpjam_device_edit_page(){
	global $wpdb,	$current_admin_url;
	$id				= isset($_GET['id'])?$_GET['id']:'';
	$duplicate_id	= isset($_GET['duplicate_id'])?$_GET['duplicate_id']:'';
	$action			= isset($_GET['action'])?$_GET['action']:'';

	$nonce_action	= $id ? 'edit-device-'.$id : 'add-device';

	$form_fields = array(
		'device'	=> array('title'=>'手机型号',	'type'=>'text'),
		'name'		=> array('title'=>'名称',	'type'=>'text'),
		'brand'		=> array('title'=>'品牌',	'type'=>'text'),
		'size'		=> array('title'=>'屏幕尺寸',	'type'=>'text')
	);

	if( $_SERVER['REQUEST_METHOD'] == 'POST' ){

		$data = wpjam_get_form_post($form_fields, $nonce_action);

		if($id){
			if($wpdb->update($wpdb->devices,$data,array('id'=>$id))){
				wpjam_admin_add_error('修改成功');
				$data['id'] = $id;
				wpjam_update_remote_device($data);
			}else{
				wpjam_admin_add_error('未修改');
			}
		}else{
			if($wpdb->insert($wpdb->devices,$data)){
				$data['id'] = $wpdb->insert_id;
				wpjam_update_remote_device($data);
				wpjam_admin_add_error('添加成功');
			}else{
				wpjam_admin_add_error('添加失败','error');
			}
		}
	}
	
	if(($action == 'edit' && $id) || ($action == 'add' && $duplicate_id)){
		if($action == 'edit' && $id){
			$device	= $wpdb->get_row($wpdb->prepare("SELECT * FROM $wpdb->devices WHERE id=%d LIMIT 1",$id));
		}elseif($action == 'add' && $duplicate_id){
			$device	= $wpdb->get_row($wpdb->prepare("SELECT * FROM $wpdb->devices WHERE id=%d LIMIT 1",$duplicate_id));
		}
		
		foreach ($form_fields as $key => $form_field) {
			$form_fields[$key]['value']	= isset($device->$key)?$device->$key:'';
		}
	}

	$form_url		= ($action == 'add')?$current_admin_url.'&action=add':$current_admin_url.'&action=edit&id='.$id;
	$action_text	= $id?'修改':'新增';
	?>

	<h2 id="edit"><?php echo $action_text;?>手机型号</h2>

	<?php wpjam_form($form_fields, $form_url, $nonce_action, $action_text); ?>
<?php
}


function wpjam_update_remote_device($data){
	$data['mysql_id'] = $data['id'];
	unset($data['id']);

	$url = 'http://172.16.3.120:8810/device/update';

	return wpjam_remote_request(
		$url, 
		array(
			'method'	=> 'POST',
			'body'		=> $data,
			'blocking'	=> false,
			'need_json_decode'	=> false
		)
	);
}

function wpjam_delete_remote_device($id){
	$data = array('mysql_id' => $id);

	$url = 'http://172.16.3.120:8810/device/delete';

	return wpjam_remote_request(
		$url, 
		array(
			'method'	=> 'POST',
			'body'		=> $data,
			'blocking'	=> false
		)
	);
}